<template>
  <basic-container>
    <div class="rule">
      <div class="rule-title">发布视频</div>
      <div style="float: right;padding-right: 210px">
        <el-button type="primary" size="small" @click="saveVideo()">保存</el-button>
        <el-button type="info" size="small" >重置</el-button>
      </div>
      <table width="1000px" border="1">
        <tr>
          <td width="130" class="right" height="60">上传视频：</td>
          <td colspan="3">
            <el-upload class="avatar-uploader"
                       action="上传地址"
                       v-bind:data="{FoldPath:'上传目录',SecretKey:'安全验证'}"
                       v-bind:on-progress="uploadVideoProcess"
                       v-bind:on-success="handleVideoSuccess"
                       v-bind:before-upload="beforeUploadVideo"
                       v-bind:show-file-list="false">
              <video v-if="inForm.videoUrl !='' && !videoFlag"
                     v-bind:src="inForm.videoUrl"
                     class="avatar video-avatar"
                     controls="controls">
                您的浏览器不支持视频播放
              </video>
              <i v-else-if="inForm.videoUrl =='' && !videoFlag"
                 class="el-icon-plus avatar-uploader-icon"></i>
              <el-progress v-if="videoFlag == true"
                           type="circle"
                           v-bind:percentage="videoUploadPercent"
                           style="margin-top:7px;"></el-progress>
            </el-upload>
          </td>
        </tr>
        <tr>
          <td width="130" class="right" height="40">视频名称：</td>
          <td>
            <el-input size="mini" v-model="inForm.videoName" class="my-el-input" placeholder="请输入内容"></el-input>
          </td>
          <td width="130" class="right" height="40">视频大小：</td>
          <td></td>
        </tr>
        <tr>
          <td width="130" class="right" height="40">允许快放：</td>
          <td>
            <el-select size="mini" class="my-el-input" v-model="inForm.isForward" placeholder="请选择">
              <el-option
                v-for="item in isForward"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </td>
          <td width="130" class="right" height="40">红包类型：</td>
          <td>
            <el-select size="mini" class="my-el-input" v-model="inForm.redEnvelopeType" placeholder="请选择">
              <el-option
                v-for="item in redEnvelopeType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td width="130" class="right" height="40">最小金额（分）</td>
          <td>
            <el-input-number size="mini" v-model="inForm.redEnvelopeMin" controls-position="right" class="my-el-input" :min="1" :max="10000"></el-input-number>
          </td>
          <td width="130" class="right" height="40">最大金额（分）</td>
          <td>
            <el-input-number size="mini" v-model="inForm.redEnvelopeMax" controls-position="right" class="my-el-input" :min="1" :max="10000"></el-input-number>
          </td>
        </tr>
        <tr>
          <td width="130" class="right">题库维护：</td>
          <td colspan="3">
            <el-button icon="el-icon-plus" size="small" round @click="showQuestion()">创建题目</el-button>
            <el-table
              :data="questionList"
              border
              style="width: 100%">
              <el-table-column
                prop="subject"
                label="题目"
                width="520">
              </el-table-column>
              <el-table-column
                prop="questionType"
                label="类型"
                width="80" :formatter = "questionTypeTest">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini" @click="showQuestionItem(scope.row.id)">选项维护</el-button>
                  <el-button
                    size="mini" @click="showEditQuestion(scope.row.id)">编辑</el-button>
                  <el-button
                    size="mini" @click="delQuestion(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </td>
        </tr>
        <tr>
          <td width="130" class="right">所属群组：</td>
          <td colspan="3">
            <el-button icon="el-icon-plus" size="small" round @click="showGroupList()">添加群组</el-button>
            <el-table
              :data="selectedGroupList"
              border
              style="width: 100%">
              <el-table-column
                prop="groupName"
                label="群组名称"
                width="740">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini" @click="removeGroupvideo(scope.row)">移除群组</el-button>
                </template>
              </el-table-column>
            </el-table>
          </td>
        </tr>
      </table>
    </div>

    <el-dialog title="题库维护" :close-on-click-modal="false" :visible.sync="dialogQuestionVisible">
      <el-form :model="questionForm" label-width="100px">
        <el-form-item label="题目：">
          <el-input type="textarea" @input="msgChange($event)" :rows="2" v-model="questionForm.subject"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="questionForm.questionType" placeholder="请选择类型">
            <el-option v-for="item in questionType" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQuestionVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveQuestion()">保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选项维护" :close-on-click-modal="false" :visible.sync="dialogQuestionItemVisible">
      <avue-crud ref="crud" :option="questionItemOption" :data="questionItemList" @row-del="removeQuestionitem" @row-update="addUpdate" @row-click="handleRowClick">
        <template slot-scope="{row,index}" slot="menu">
          <el-button type="text" size="small" @click="rowCell(row,index)">{{row.$cellEdit?'保存':'编辑'}}</el-button>
        </template>
      </avue-crud>
    </el-dialog>

    <el-dialog title="视频群组" :close-on-click-modal="false" :visible.sync="dialogGroupListVisible">
      <el-table
        ref="multipleTable"
        :data="allGroupList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="groupName" label="群组名称" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="userId" label="管理员" width="120">
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-button @click="toggleSelection()">全选</el-button>
        <el-button @click="groupSelectionSave()">保存</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {add,getDetailVideo} from "@/api/videoanswer/video";
import {update,getDetailQuestion,getQuestionList,delQuestion} from "@/api/videoanswer/question";
import {getQuestionitemList, addQuestionitem, removeQuestionitem} from "@/api/videoanswer/questionitem";
import {noPagelist} from "@/api/videoanswer/group";
import {batchSubmit,getGroupListByVideoid,removeGroupvideo} from "@/api/videoanswer/groupvideo";
export default {
  name: "editVideo",
  data() {
    return {
      //表单数据
      inForm: {},
      //题库表单数据
      questionForm:{},
      //红包类型下拉菜单
      redEnvelopeType: [{value:1,label:'区间'},{value:2,label:'固定'}],
      //是否快放下拉菜单
      isForward: [{value:1,label:'是'},{value:0,label:'否'}],
      //题目类型
      questionType: [{value: 1,label: '单选'}, {value: 2,label: '多选'}],
      //维护选项当前题目id
      currentQuestionId:0,
      //
      videoFlag: false,
      //是否显示进度条
      videoUploadPercent: "",
      //进度条的进度，
      isShowUploadVideo: false,
      dialogQuestionItemVisible: false,
      dialogGroupListVisible: false,
      dialogQuestionVisible: false,
      questionList: [],
      //题库弹出框初始化数据
      questionItemList:[],
      selectedGroupList: [],
      questionItemOption:{
        menuWidth:100,
        addBtn:false,
        editBtn:false,
        addRowBtn:true,
        cellBtn:false,
        cancelBtn:false,
        column: [{
          label:'序号',
          prop: 'itemNo',
          width: 80,
          cell: true,
          type:'select',
          dicData:[
            {label:'A',value:'A'},
            {label:'B',value:'B'},
            {label:'C',value:'C'},
            {label:'D',value:'D'},
            {label:'E',value:'E'}]
        },{
          label:'选项',
          prop: 'optionsItem',
          cell: true
        },{
          label:'是否答案',
          prop: 'isCorrect',
          type:'select',
          width: 100,
          dicData:[{
            label:'否',
            value:'0'
          },{
            label:'是',
            value:'1'
          }],
          cell: true
        }]
      },
      allGroupList: [],
      multipleSelection: []
    }
  },
  created() {
    let param = this.$route.query;
    if(typeof(param.row) !== "undefined"){
      let id = param.row;
      this.initForm(id);
    }
  },
  methods: {
    //初始化表单
    initForm(id){
      getDetailVideo(id).then(res => {
        this.inForm = res.data.data.video;
        this.questionList = res.data.data.questionList;
        this.selectedGroupList = res.data.data.groupList;
      });
    },
    //上传前回调
    beforeUploadVideo(file) {
      var fileSize = file.size / 1024 / 1024 < 50;
      if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      if (!fileSize) {
        this.$message.error("视频大小不能超过50MB");
        return false;
      }
      this.isShowUploadVideo = false;
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    //上传成功回调
    handleVideoSuccess(res, file) {
      this.isShowUploadVideo = true;
      this.videoFlag = false;
      this.videoUploadPercent = 0;

      //前台上传地址
      if (file.status == 'success' ) {
         this.inForm.videoUrl = file.url;
      } else {
        this.$message.error("上传失败，请重新上传");
      }

      //后台上传地址
      if (res.Code == 0) {
        this.inForm.videoUrl = res.Data;
      } else {
        this.$message.error(res.Message);
      }
    },
    //
    saveVideo(){
      add(this.inForm).then(res => {
        debugger;
        this.$message({
          type: "success",
          message: "保存成功!"
        });
        this.inForm = res.data.data;
      }, error => {
        console.log(error);
      });
    },
    //弹出题库选项维护
    showQuestionItem(id){
      this.currentQuestionId = id;
      getQuestionitemList({questionId:id}).then(res => {
        this.questionItemList = res.data.data;
      });
      this.dialogQuestionItemVisible = true;
    },
    //弹出编辑题目
    showEditQuestion(id){
      getDetailQuestion(id).then(res => {
        this.questionForm = res.data.data;
      });
      this.dialogQuestionVisible = true;
    },
    //删除题目
    delQuestion(row){
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return delQuestion(row.id);
        })
        .then(() => {
          getQuestionList({videoId:row.videoId}).then(res1 => {
            this.questionList = res1.data.data;
          });
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    //弹出题库维护
    showQuestion(){
      if(typeof(this.inForm.id) === "undefined"){
        this.$message.error("请先保存视频信息！");
      } else {
        this.questionForm = {};
        this.questionForm.videoId = this.inForm.id;
        this.dialogQuestionVisible = true;
      }
    },
    showGroupList(){
      if(typeof(this.inForm.id) === "undefined"){
        this.$message.error("请先保存视频信息！");
      } else {
        this.questionForm.videoId = this.inForm.id;
        noPagelist(this.selectedGroupList).then(res1 => {
          this.allGroupList = res1.data.data;
        });
        this.dialogGroupListVisible = true;
      }
    },
    //移除群组
    removeGroupvideo(row){
      this.$confirm("确定移除群组?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeGroupvideo({videoId:this.inForm.id,groupId:row.id});
        })
        .then(() => {
          getGroupListByVideoid({videoId:this.inForm.id}).then(res1 => {
            this.selectedGroupList = res1.data.data;
          });
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    //保存题库
    saveQuestion(){
      update(this.questionForm).then(res => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        getQuestionList({videoId:res.data.data.videoId}).then(res1 => {
          this.questionList = res1.data.data;
        });
        this.dialogQuestionVisible = false;
      }, error => {
        console.log(error);
      });

    },
    rowCell(row, index) {
      this.$refs.crud.rowCell(row, index)
    },
    addUpdate(form,index,done,loading){
      form.questionId = this.currentQuestionId;
      addQuestionitem(form).then(res => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.questionItemList[index] = res.data.data;
        done();
      }, error => {
        console.log(error);
      });
    },
    removeQuestionitem(form,index){
      let questionItem = this.questionItemList[index];
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeQuestionitem(questionItem.id);
        })
        .then(() => {
          this.showQuestionItem(questionItem.questionId);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    rowUpdate(form, index, done) {
      this.$message.success(
        '编辑数据' + JSON.stringify(form) + '数据序号' + index
      )
      done()
    },
    handleRowClick(row, event, column) {
      console.log(row.$index);
    },
    msgChange(e){
      this.$forceUpdate();
    },
    questionTypeTest(row, column){
      if(row.questionType === 1){
        return '单选';
      } else {
        return '多选';
      }
    },
    toggleSelection() {
      this.allGroupList.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row);
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    groupSelectionSave(){
      let list = [];
      this.multipleSelection.forEach(row => {
        let item = {groupId:row.id,videoId:this.inForm.id};
        list.push(item);
      });
      batchSubmit(list).then(res => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        getGroupListByVideoid({videoId:this.inForm.id}).then(res1 => {
          this.selectedGroupList = res1.data.data;
        });
        this.dialogGroupListVisible = false;
      }, error => {
        console.log(error);
      });
    }
  }
}
</script>

<style>
.rule {
  margin: 20px 20px;
}
.rule .rule-title {
  font-weight: 700;
  float: left;
}
.my-el-input {
  width: 300px;
}
.right{
  text-align: right;
}
</style>
